"use strict";
import tinify from "tinify";
import path from "path";
import fs from "fs";
const successColor = "\x1B[32m";
const warningColor = "\x1B[33m";
const errorColor = "\x1B[31m";
let compressionsThisMonth;
const getCount = () => {
  new Promise((resolve) => {
    tinify.validate(function (err) {
      if (err) return (compressionsThisMonth = 0);
      // Validation of API key failed.
      compressionsThisMonth = tinify.compressionCount;
      resolve();
    });
  });
};
const getFileInfo = (dir) => {
  return new Promise((resolve, reject) => {
    fs.stat(dir, function (err, stats) {
      if (err) return reject(err.message);
      return resolve(stats);
    });
  });
};

// 符合的压缩的文件（webp、jpg、jpeg、png）返回
const getDirFiles = async (dir) => {
  const files = [];
  const fullpath = path.resolve(path.resolve(), dir);
  const list = fs.readdirSync(fullpath);
  for (let item of list) {
    const newDir = path.resolve(fullpath, item);
    const stats = await getFileInfo(newDir);
    if (stats.isDirectory()) {
      files.push(...(await getDirFiles(path.join(dir, item))));
    } else {
      files.push({ path: newDir, size: stats.size });
    }
  }
  return files;
};
const done = () => {
  let newCount = tinify.compressionCount;
  console.log(
    errorColor,
    `压缩执行完成！！！本次压缩${
      newCount - compressionsThisMonth
    }次，该插件共帮助开发者压缩${compressionsThisMonth}次`
  );
};
const compressionInfo = (source, item) => {
  return new Promise((resolve) => {
    source.toFile(item.path, async (err) => {
      if (err) {
        return resolve({
          color: errorColor,
          message: `${item.path} 压缩失败：${err.message}`,
        });
      }
      const comItem = await getFileInfo(item.path);
      return resolve({
        color: successColor,
        message: `${item.path} 压缩成功！压缩前${Math.floor(
          item.size / 1000
        )}kb，压缩后${Math.floor(comItem.size / 1000)}kb`,
      });
    });
  });
};
const tinifyFile = async (
  dir = "./src/assets",
  key = "cxgnKZcd5lTkqytxlTgvVFCmsSZ5wrqs"
) => {
  const list = await getDirFiles(dir);
  tinify.key = key;
  await getCount();
  let c = 0;
  for (let item of list) {
    if (!/\.(png|webp|jpeg|jpg)$/.test(item.path)) {
      c++;
      console.log(warningColor, `${item.path} 不支持压缩已跳过`);
    } else {
      const source = tinify.fromFile(item.path);
      compressionInfo(source, item).then(({ color, message }) => {
        console.log(color, message);
        c++;
        if (c === list.length) {
          done();
        }
      });
    }
  }
};
export default tinifyFile;
